package com.boot.security.server.config;

import com.boot.security.server.model.user.TswUser;
import org.apache.catalina.Session;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    //在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        TswUser tswUser =(TswUser) request.getSession().getAttribute("user");
        if (tswUser != null) {
            return true;
        } else {
            System.out.println("MyInterceptor拦截成功-----------------");
            request.setAttribute("msg","登录成功");
            response.sendRedirect(request.getContextPath() + "/wechatLogin/userAuth");
            /*request.getRequestDispatcher("/home/login/login.html").forward(request,response);*/
            return false;
        }
            //如果false，停止流程，api被拦截
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle被调用");
    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion被调用");
    }
}
